package com.yifang.yibingproject.config;

import com.yifang.yibingproject.exception.*;
import com.yifang.yibingproject.utils.Result;
import com.yifang.yibingproject.utils.ResultUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestControllerAdvice
public class GlobalControllerAdvice {

    private static final Logger log = LoggerFactory.getLogger(com.yifang.yibingproject.config.GlobalControllerAdvice.class);

    @ExceptionHandler(ParamException.class)
    public Result paramException(ParamException e) {
        log.error(e.getMessage(), e);
        return ResultUtils.fail(-1, e.getMessage());
    }

    @ExceptionHandler(ServiceException.class)
    public Result serviceException(ServiceException e) {
        log.error(e.getMessage(), e);
        return ResultUtils.fail(-2, e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result exception(Exception e) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String time = sdf.format(new Date());
        String error = "[" + time + "]" + e.getMessage();
        log.error(error, e);
        return ResultUtils.fail(-3, error);
    }

    @ExceptionHandler(AccessDeniedException.class)
    public Result accessDeniedException(AccessDeniedException e) {
        log.error(e.getMessage());
        return ResultUtils.fail(-7, "权限不足");
    }


    @ExceptionHandler(NotMemberException.class)
    public Result notMemberException(NotMemberException e) {
        log.error(e.getMessage());
        return ResultUtils.fail(-11, e.getMessage());
    }

    @ExceptionHandler(DetailException.class)
    public Result detailException(DetailException e) {
        log.error(e.getMessage(), e);
        return ResultUtils.fail(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(NotLoginException.class)
    public Result notLoginException(NotLoginException e) {
        return ResultUtils.fail(-4, e.getMessage());
    }
}
